// eslint-disable-next-line
import {
  getPerCost,
  savePerCost
} from '../../api/customer'
import {
  COST_LIST,
  COST_CURRENT_ROW,
  COST_DATA_COUNT,
  COST_HISTORY_DATA,
  COST_UPLOAD_LIST
} from '../motations-type'

export default {
  state: {
    costData: [],
    costDataCount: null,
    pageSize: 20,
    costHistoryData: [],
    row: {
      proname: '',
      ctime: '',
      price: ''
    }
  },
  getters: {
    costData: state => state.costData
  },
  mutations: {
    [COST_LIST] (state, data) {
      state.costData = data
    },
    [COST_CURRENT_ROW] (state, data) {
      state.row = data
    },
    [COST_DATA_COUNT] (state, data) {
      state.costDataCount = data
    },
    [COST_HISTORY_DATA] (state, data) {
      state.costHistoryData = data
    },
    [COST_UPLOAD_LIST] (state, data) {
      state.costData = state.costData.push(data)
    }
  },
  actions: {
    async getPerCostList ({ commit, rootState }, playload) {
      let data = {}
      let newData = []
      if (Object.keys(playload).length > 0) {
        data = playload
      }
      const resp = await getPerCost(data)
      resp.data.data.rows.map((item) => {
        newData = [...newData, {
          id: item.id ? item.id : '-',
          proname: item.name,
          proid: item.proid,
          ctime: item.ctime,
          price: item.price,
          cz: item.cz
        }]
      })
      commit(COST_LIST, newData)
      commit(COST_DATA_COUNT, resp.data.data.total)
      if (newData.length < rootState.perCost.pageSize) {
        commit(COST_HISTORY_DATA, newData)
      } else {
        commit(COST_HISTORY_DATA, newData.slice(0, rootState.perCost.pageSize))
      }
    },
    async changePerCostPage ({ commit, rootState }, index) {
      let data = rootState.perCost.costData
      let _start = (index - 1) * rootState.perCost.pageSize
      let _end = index * rootState.perCost.pageSize
      commit(COST_HISTORY_DATA, data.slice(_start, _end))
    },
    async getPerCostCurrentRow ({ commit, rootState }, row) {
      commit(COST_CURRENT_ROW, row)
    },
    async savePerCostData ({ commit, rootState }, playload) {
      let data = {}
      if (Object.keys(playload).length > 0) {
        data = playload
      }
      await savePerCost(data)
    },
    async getPerCostUploadList ({ commit, rootState }, uploadList) {
      commit(COST_UPLOAD_LIST, uploadList)
    }
  }
}
